package cn.ibizlab.odoo.webcrm.security.filter;

import java.util.ArrayList;
import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import cn.ibizlab.odoo.webcrm.security.token.TokenManager;
import cn.ibizlab.odoo.util.security.userdetail.LoginUser;
import cn.ibizlab.odoo.util.log.IBIZLog;

@Slf4j
@IBIZLog
public class LoginFilter extends UsernamePasswordAuthenticationFilter {

    private AuthenticationManager authenticationManager;
    private TokenManager tokenManager;

    public LoginFilter(AuthenticationManager authenticationManager, TokenManager tokenManager) {
        this.authenticationManager = authenticationManager;
        this.tokenManager = tokenManager;
        this.setPostOnly(false);
        this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/login"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res)
            throws AuthenticationException {

        String strUserName = req.getParameter("username") ;
        String strPassword = req.getParameter("password") ;
        return authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(strUserName, strPassword, new ArrayList<>()));

    }

    @Override
    protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain,
                                            Authentication auth) throws IOException, ServletException {
        LoginUser user = (LoginUser) auth.getPrincipal();

        String token = tokenManager.generateToken(user);



        ObjectMapper mapper = new ObjectMapper();
        res.setStatus(HttpStatus.OK.value());
        res.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        mapper.writeValue(res.getWriter(), token);
    }

    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
                                              AuthenticationException e) throws IOException, ServletException {
        response.setStatus(HttpStatus.OK.value());
        ObjectMapper mapper = new ObjectMapper();

        if (e instanceof BadCredentialsException) {

        } else if (e instanceof UsernameNotFoundException) {

        } else if (e instanceof AuthenticationCredentialsNotFoundException) {

        } else if (e instanceof ProviderNotFoundException) {

        } else {

        }

        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        mapper.writeValue(response.getWriter(), "登陆失败");

    }

}
